import requests
import time
import json
from configloader import ConfigLoader
from component.clustercommunication import ClusterCommunication

previous_request_num = 0
TARGET_NETWORK_METRICS = 'nginx_http_requests_total'
DEBUG_ADDRESS = '127.0.0.1:60184'

cl = ConfigLoader.get_instance()
cluster = ClusterCommunication.get_instance()

class Monitoring:
    @staticmethod
    def get_nginx_request_step():
        prometheus_api_prefix = cluster.get_prometheus_address_and_port() if cl.debug == 0 else DEBUG_ADDRESS
        previous = time.time() - cl.duration
        url = "http://" + prometheus_api_prefix + "/" + "api/v1/query?query=" + TARGET_NETWORK_METRICS
        res = requests.get(url)
        url_pre = "http://" + prometheus_api_prefix + "/" + "api/v1/query?query=" + TARGET_NETWORK_METRICS + "&time=" + str(
            previous)
        res_pre = requests.get(url_pre)
        metrics = json.loads(res.text).get('data').get('result')
        metrics_pre = json.loads(res_pre.text).get('data').get('result')
        dev2request = []
        ipMap = cluster.get_ip_map_service()
        dev2request_map = {}
        for metric in metrics:
            if metric['metric']['job'] == 'kubernetes-pods':
                dict = {}
                ipAndPort = str(metric['metric']['instance'])
                ip = ipAndPort.split(':')[0]
                dev = ipMap.get(ip)
                dict[dev] = int(metric['value'][1])
                dev2request_map[dev] = int(metric['value'][1])

        for metric in metrics_pre:
            if metric['metric']['job'] == 'kubernetes-pods':
                ipAndPort = str(metric['metric']['instance'])
                ip = ipAndPort.split(':')[0]
                dev = ipMap.get(ip)
                dev2request_map[dev] -= int(metric['value'][1])

        for k in dev2request_map:
            dict = {}
            dict[k] = dev2request_map[k]
            dev2request.append(dict)

        return dev2request

    @staticmethod
    def get_workload_rate(namespace="default"):
        rates = Monitoring.get_nginx_request_step()
        # div by STEP
        for item in rates:
            for k in item:
                item[k] /= cl.duration
        return rates

